import {Button, Input, Text, View} from '@tarojs/components'
import Taro from '@tarojs/taro'
import {useEffect, useState} from 'react'
import {login, register} from '@/api'
import {isLoggedIn, setToken, setUserInfo} from '@/utils/auth'

export default function Login() {
  const [isLogin, setIsLogin] = useState(true)
  const [phone, setPhone] = useState('')
  const [password, setPassword] = useState('')
  const [email, setEmail] = useState('')
  const [loading, setLoading] = useState(false)

  useEffect(() => {
        if (isLoggedIn()) {
          setTimeout(() => {
            Taro.switchTab({url: '/pages/home/index'})
          }, 1500)
          return
        }  
  })


  const handleSubmit = async () => {
    if (!phone || !password) {
      Taro.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }

    if (!/^1[3-9]\d{9}$/.test(phone)) {
      Taro.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      })
      return
    }

    if (password.length < 6) {
      Taro.showToast({
        title: '密码至少6位',
        icon: 'none'
      })
      return
    }

    setLoading(true)

    try {
      const result = isLogin
        ? await login({phone, password})
        : await register({phone, password, email: email || undefined})

      if (result.success && result.data) {
        setToken(result.data.token)
        setUserInfo(result.data.user)

        Taro.showToast({
          title: isLogin ? '登录成功' : '注册成功',
          icon: 'success'
        })

        setTimeout(() => {
          Taro.switchTab({url: '/pages/home/index'})
        }, 1500)
      } else {
        Taro.showToast({
          title: result.error || '操作失败',
          icon: 'none'
        })
      }
    } catch (error: any) {
      Taro.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }

  return (
    <View className="min-h-screen flex flex-col bg-gradient-to-b from-blue-50 to-white">
      <View className="flex-1 flex flex-col justify-center px-8">
        <View className="mb-12 text-center">
          <Text className="text-3xl font-bold text-blue-900 block mb-2">艺术空间票务</Text>
          <Text className="text-sm text-gray-600 block">专业的展览门票在线销售平台</Text>
        </View>

        <View className="bg-white rounded-2xl shadow-lg p-6">
          <View className="flex mb-6 bg-gray-100 rounded-lg p-1">
            <View
              className={`flex-1 text-center py-2 rounded-lg transition-all ${
                isLogin ? 'bg-blue-600' : 'bg-transparent'
              }`}
              onClick={() => setIsLogin(true)}>
              <Text className={`text-sm ${isLogin ? 'text-white font-bold' : 'text-gray-600'}`}>登录</Text>
            </View>
            <View
              className={`flex-1 text-center py-2 rounded-lg transition-all ${
                !isLogin ? 'bg-blue-600' : 'bg-transparent'
              }`}
              onClick={() => setIsLogin(false)}>
              <Text className={`text-sm ${!isLogin ? 'text-white font-bold' : 'text-gray-600'}`}>注册</Text>
            </View>
          </View>

          <View className="space-y-4">
            <View>
              <Text className="text-sm text-gray-700 mb-2 block">手机号</Text>
              <Input
                type="number"
                maxlength={11}
                placeholder="请输入手机号"
                value={phone}
                onInput={(e) => setPhone(e.detail.value)}
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:border-blue-600 focus:outline-none"
              />
            </View>

            {!isLogin && (
              <View>
                <Text className="text-sm text-gray-700 mb-2 block">邮箱（可选）</Text>
                <Input
                  type="text"
                  placeholder="请输入邮箱"
                  value={email}
                  onInput={(e) => setEmail(e.detail.value)}
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:border-blue-600 focus:outline-none"
                />
              </View>
            )}

            <View>
              <Text className="text-sm text-gray-700 mb-2 block">密码</Text>
              <Input
                type="text"
                password
                placeholder="请输入密码（至少6位）"
                value={password}
                onInput={(e) => setPassword(e.detail.value)}
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:border-blue-600 focus:outline-none"
              />
            </View>

            <Button
              onClick={handleSubmit}
              disabled={loading}
              className="w-full bg-blue-600 text-white py-3 rounded-lg font-bold text-base mt-6"
              style={{
                backgroundColor: loading ? '#93c5fd' : '#2563eb',
                color: 'white',
                border: 'none'
              }}>
              {loading ? '处理中...' : isLogin ? '登录' : '注册'}
            </Button>
          </View>

          {isLogin && (
            <View className="mt-4 text-center">
              <Text className="text-xs text-gray-500">测试账号：13800138000 密码：123456</Text>
            </View>
          )}
        </View>

        <View className="mt-6 text-center">
          <Text className="text-xs text-gray-500">登录即表示同意《用户协议》和《隐私政策》</Text>
        </View>
      </View>
    </View>
  )
}
